import { Message } from '@arco-design/web-react';
import main from '@src/main';
import { saveAs } from 'file-saver';

// 导入表
export async function apiImportGenTable(tabs: string) {
  return await main.api.post(`/code/gen/importTable?tables=${tabs}`, {}, { headers: { datasource: 'master' } });
}

// 获取字典列表
export async function apiGetDictOptionList() {
  return await main.api.get('/system/dict/type/optionselect', { headers: { datasource: 'master' } });
}
// 同步
export async function apiSyncTable(tableName: string) {
  return await main.api.get(`/code/gen/synchDb/${tableName}`, { headers: { datasource: 'master' } });
}

// 代码预览
export async function apiPreViewCode(tableId: string) {
  return await main.api.get(`/code/gen/preview/${tableId}`, { headers: { datasource: 'master' } });
}

// 生成代码 自定义路径
export async function apiCreateCode(tableNames: string) {
  return await main.api.get(`/code/gen/genCode/${tableNames}`, { headers: { datasource: 'master' } });
}
// 生成代码 zip
export async function apiCreateCodeZip(tableNames: string) {
  let res = await main.api.get(`/code/gen/download/${tableNames}`, {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded', datasource: 'master' },
    responseType: 'blob',
  });
  let data = res.data;
  let isBlob = await blobValidate([data]);
  if (isBlob) {
    let blob = new Blob([data as unknown] as BlobPart[]);
    saveAs(blob, 'react.zip');
  } else {
    // @ts-ignore
    let resText = await data.text();
    let rspObj = JSON.parse(resText);
    Message.error(rspObj.msg || '系统未知错误，请反馈给管理员');
  }

  return res;
}
// 验证是否为blob格式
export async function blobValidate(data: any) {
  try {
    const text = await data.text();
    JSON.parse(text);
    return false;
  } catch (error) {
    return true;
  }
}
